using Microsoft.EntityFrameworkCore;
using NetworkFlowMonitor.Scripts.Service;

namespace NetworkFlowMonitor.Scripts.Data;

// Data/ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public DbSet<Device> Devices { get; set; }
    public DbSet<TrafficRecord> TrafficRecords { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 设备表配置
        modelBuilder.Entity<Device>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.HasIndex(e => e.MacAddress).IsUnique();
            entity.HasIndex(e => e.IpAddress);
            entity.Property(e => e.DeviceName).HasMaxLength(100);
            entity.Property(e => e.Manufacturer).HasMaxLength(100);
        });

        // 流量记录表配置
        modelBuilder.Entity<TrafficRecord>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.HasIndex(e => e.Timestamp);
            entity.HasIndex(e => e.DeviceId);
            entity.HasOne(d => d.Device)
                .WithMany(p => p.TrafficRecords)
                .HasForeignKey(d => d.DeviceId)
                .OnDelete(DeleteBehavior.Cascade);
        });
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlite("Data Source=../traffic_monitor.db");

            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Error); // 🔽 只显示 Warning 及以上级别
            });


            optionsBuilder.UseLoggerFactory(loggerFactory);
        }
    }
}